#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

#define NAME_LEN 10
#define COUNT 20

typedef struct student {
	char name[NAME_LEN];
	size_t namesize;
	int grade;
} stu_t;

int cmp_stu_descend(stu_t a, stu_t b)
{
	return a.grade < b.grade;
}

void sort(stu_t* arr, int cnt, int (*cmp)(stu_t, stu_t));

int main(void)
{
	stu_t arr[COUNT];
	int i = 0;
	int j = 0;
	char* str;
	char c;

	srand(time(NULL));

	for (i = 0; i < COUNT; i++) {
		str = arr[i].name;

		j = 0;

		do {
			scanf("%c", &(str[j]));
			j++;
		} while (str[j - 1] != '\n' && j < NAME_LEN);

		str[j - 1] = '\0';

		// 手动输入分数
		/*
		scanf("%d", &(arr[i].grade));

		do {
			scanf("%c", &c);
		} while (c != '\n'); // 吃掉数字后的换行
		*/

		// 随机生成分数
		arr[i].grade = rand() % 101;
	}

	printf("列表：\n");
	for (i = 0; i < COUNT; i++) {
		printf("[%s] (%d)\n", arr[i].name, arr[i].grade);
	}

	// 按成绩排序
	sort(arr, COUNT, cmp_stu_descend);

	printf("排序后列表：\n");
	for (i = 0; i < COUNT; i++) {	
		printf("[%s] (%d)\n", arr[i].name, arr[i].grade);
	}
	
	return 0;
}

void sort(stu_t* arr, int cnt, int (*cmp)(stu_t, stu_t))
{
	int i, j;
	stu_t t;

	for (i = 0; i < cnt - 1; i++) {
		for (j = 0; j < cnt - i - 1; j++) {
			if (cmp(arr[j], arr[j + 1])) {
				t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
		}
	}
}
